# -*- coding: utf-8 -*-
import json
import subprocess
import time
import re

from flask import Flask, request, jsonify

from client import Client
from threading import Thread

from arguments import get_args
from moviepy.editor import VideoFileClip

app = Flask(__name__)
app.debug = True


# 分割语义文本函数，按照字符数量分割
def cut_text(obj, sec):
    return [obj[i:i+sec] for i in range(0, len(obj), sec)]


# 分割语义文本函数，按照标点符号分割
def segmentation_text(text):
    pattern = r'\.|/|;|\'|`|\[|\]|<|>|\?|:|"|\{|\}|\~|!|@|#|\$|%|\^|&|\(|\)|-|=|\_|\+|。|、|；|‘|’|【|】|·|！| |…|（|）|,|、|，'
    out_text = re.split(pattern, text)
    print(out_text)
    return out_text


# flask服务器，接受请求，内容为语义文本
@app.route('/general_video', methods=['post'])
def general_long_video():
    if not request.data:
        return jsonify(code=300,
                       msg='ok',
                       data='fail')

    # time_start = time.time()  # 记录开始时间

    params = request.data.decode('utf-8')
    prams = json.loads(params)

    worker_num = len(Clients)                        # worker 数量统计
    string_len = len(prams['text'])                  # 文本长度统计
    single_len = int(string_len / worker_num) + 1    # worker 均分文本长度
    out_text = cut_text(prams['text'], single_len)   # 文本分割

    # 多线程并发分配任务
    for index, client in enumerate(Clients):
        print(out_text[index])
        if index < len(Clients) - 1:
            Thread(target=Clients[index].allocating_task, args=(out_text[index], str(index))).start()
        # 最后一个被分配视频生成任务服务器作为瓶颈
        elif index == len(Clients) - 1:
            Thread(target=Clients[index].allocating_task, args=(out_text[index], str(index))).run()

    time.sleep(1)                                               # 缓冲时间，避免有视频生成任务未完成
    command = 'bash addNewFragment.sh'                          # 整合生成好的视频内容
    subprocess.Popen(command, shell=True)
    # function()   执行的程序
    # time_end = time.time()  # 记录结束时间
    # time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
    time.sleep(1)
    video_path = args.stream1_path      # '/home/ynos/streaming_chen/content/stream1.mp4'
    clip = VideoFileClip(video_path)

    '''
    one_line = str(time_sum) + ' ' + str(clip.duration) + '\n'
    with open('time_log.txt', 'a') as f:
        f.write(one_line)
    '''

    time.sleep(int(clip.duration)+1)
    command = 'bash recovery.sh'                                 # 推流完成，还原初始状态
    subprocess.Popen(command, shell=True)

    return jsonify(code=200,
                   msg='ok',
                   data='success')


if __name__ == '__main__':
    args = get_args()

    # 配置多台主机，用于分布式视频生成任务
    Clients = [Client(host='10.220.138.20', port='10100'),
               Client(host='10.220.138.21', port='10100')]

    app.run(host=args.host, port=args.port)
